package com.ruoyi.car.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @Author wy
 * @Description TODO
 * @Date 2023/5/31 14:59
 * @Version 1.0
 */
@Configuration
public class EsConfig {

    @Autowired
    private ElasticsearchRestClientProperties  elasticsearchRestClientProperties;


    @Bean
    public RestHighLevelClient  restHighLevelClient(){
        //http://192.168.21.160:9200
        String esHost=this.elasticsearchRestClientProperties.getUris().get(0);
        String[] arr=esHost.replaceAll("//","").split(":");

        RestClientBuilder builder = RestClient.builder(
                new HttpHost( arr[1], Integer.parseInt(arr[2]))
        );
        //开始设置用户名和密码
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(this.elasticsearchRestClientProperties.getUsername(), this.elasticsearchRestClientProperties.getPassword()));
        builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));

        // Create the HLRC
        RestHighLevelClient hlrc = new RestHighLevelClient(builder);
        return hlrc;
    }

}
